/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package l2s.gameserver.network.clientpackets;

import l2s.commons.configuration.Config;
import l2s.gameserver.datatables.OfflineTradersTable;
import l2s.gameserver.model.ItemRequest;
import l2s.gameserver.model.L2ItemInstance;
import l2s.gameserver.model.L2Object;
import l2s.gameserver.model.L2World;
import l2s.gameserver.model.TradeList;
import l2s.gameserver.model.TradeList.TradeItem;
import l2s.gameserver.model.actor.instance.L2PcInstance;
import l2s.gameserver.network.serverpackets.ActionFailed;
import l2s.gameserver.util.Util;

public final class RequestPrivateStoreSell extends L2GameClientPacket
{
	private int _storePlayerId;
	private int _count;
	private int _price;
	private ItemRequest[] _items;
	
	@Override
	protected void readImpl()
	{
		_storePlayerId = readD();
		_count = readD();
		
		if ((_count < 0) || ((_count * 20) > _buf.remaining()) || (_count > Config.MAX_ITEM_IN_PACKET))
		{
			_count = 0;
		}
		
		_items = new ItemRequest[_count];
		
		long priceTotal = 0;
		for (int i = 0; i < _count; i++)
		{
			int objectId = readD();
			int itemId = readD();
			int enchant = readH();
			readH();
			long count = readD();
			int price = readD();
			
			if ((count > Integer.MAX_VALUE) || (count < 0))
			{
				String msgErr = "[RequestPrivateStoreSell] player " + getClient().getActiveChar().getName() + " tried an overflow exploit, ban this player!";
				Util.handleIllegalPlayerAction(getClient().getActiveChar(), msgErr, Config.DEFAULT_PUNISH);
				_count = 0;
				_items = null;
				return;
			}
			
			_items[i] = new ItemRequest(objectId, itemId, enchant, (int) count, price);
			priceTotal += price * count;
		}
		
		if ((priceTotal < 0) || (priceTotal > Integer.MAX_VALUE))
		{
			String msgErr = "[RequestPrivateStoreSell] player " + getClient().getActiveChar().getName() + " tried an overflow exploit, ban this player!";
			Util.handleIllegalPlayerAction(getClient().getActiveChar(), msgErr, Config.DEFAULT_PUNISH);
			_count = 0;
			_items = null;
			return;
		}
		
		_price = (int) priceTotal;
	}
	
	@Override
	protected void runImpl()
	{
		L2PcInstance player = getClient().getActiveChar();
		if (player == null)
		{
			return;
		}
		
		L2PcInstance storePlayer = L2World.getInstance().getPlayer(_storePlayerId);
		if (storePlayer == null)
		{
			return;
		}
		
		if (storePlayer.getPrivateStoreType() != L2PcInstance.STORE_PRIVATE_BUY)
		{
			return;
		}
		
		TradeList storeList = storePlayer.getBuyList();
		if (storeList == null)
		{
			return;
		}
		
		if (!player.getAccessLevel().allowTransaction())
		{
			player.sendMessage("Transactions are disable for your Access Level");
			sendPacket(ActionFailed.STATIC_PACKET);
			return;
		}
		
		for (ItemRequest ir : _items)
		{
			for (TradeItem sellersItem : storeList.getItems())
			{
				if (sellersItem.getItem().getItemId() == ir.getItemId())
				{
					if (ir.getPrice() != sellersItem.getPrice())
					{
						String msgErr = "[RequestPrivateStoreSell] player " + getClient().getActiveChar().getName() + " tried to change the seller's price in a private store (buy), ban this player!";
						Util.handleIllegalPlayerAction(getClient().getActiveChar(), msgErr, Config.DEFAULT_PUNISH);
						return;
					}
					
					if (sellersItem.getEnchant() == ir.getEnchant())
					{
						L2Object o = L2World.getInstance().findObject(ir.getObjectId());
						if ((o == null) || !(o instanceof L2ItemInstance))
						{
							String msgErr = "[RequestPrivateStoreSell] player " + getClient().getActiveChar().getName() + " tried to sell null item in a private store (buy), ban this player!";
							Util.handleIllegalPlayerAction(getClient().getActiveChar(), msgErr, Config.DEFAULT_PUNISH);
							return;
						}
						
						L2ItemInstance item = (L2ItemInstance) o;
						if (ir.getEnchant() != item.getEnchantLevel())
						{
							String msgErr = "[RequestPrivateStoreSell] player " + getClient().getActiveChar().getName() + " tried to change enchant level in a private store (buy), ban this player!";
							Util.handleIllegalPlayerAction(getClient().getActiveChar(), msgErr, Config.DEFAULT_PUNISH);
							return;
						}
					}
					else
					{
						player.sendMessage("Incorect enchant level.");
						return;
					}
					break;
				}
			}
		}
		
		if (storePlayer.getAdena() < _price)
		{
			sendPacket(ActionFailed.STATIC_PACKET);
			storePlayer.sendMessage("You have not enough adena, canceling PrivateBuy.");
			storePlayer.setPrivateStoreType(L2PcInstance.STORE_PRIVATE_NONE);
			storePlayer.broadcastUserInfo();
			return;
		}
		
		if (!storeList.privateStoreSell(player, _items, _price))
		{
			sendPacket(ActionFailed.STATIC_PACKET);
			_log.warn("PrivateStore sell has failed due to invalid list or request. Player: " + player.getName() + ", Private store of: " + storePlayer.getName());
			return;
		}
		
		if (storeList.getItemCount() == 0)
		{
			storePlayer.setPrivateStoreType(L2PcInstance.STORE_PRIVATE_NONE);
			storePlayer.broadcastUserInfo();
		}
		
		// Update offline trade record in realtime
		if (Config.OFFLINE_TRADE_ENABLE && Config.RESTORE_OFFLINERS && !(storeList.getItemCount() == 0) && ((storePlayer.getClient() == null) || storePlayer.getClient().isDetached()))
		{
			OfflineTradersTable.storeOffliners();
		}
		
		if (storeList.getItemCount() == 0)
		{
			storePlayer.setPrivateStoreType(L2PcInstance.STORE_PRIVATE_NONE);
			storePlayer.broadcastUserInfo();
		}
	}
}
